import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useDebounce } from '@cfe/hooks';
import { Form, InputNumber, Radio, Space, Spin, Tooltip } from 'antd';

import { processConfidenceNumber } from '@/utils/number';
import { requestWithoutCache } from '@/utils/request';

import {
  DEFAULT_CONFIDENCE,
  MAX_CONFIDENCE,
  MIN_CONFIDENCE,
} from './constants';

const { useForm } = Form;

const CrowdCountAdjust = forwardRef(
  (
    {
      crowd_id,
      onRequest,
      onSuccess,
      minCoverage,
      maxCoverage,
      onConfidenceChange,
    },
    ref,
  ) => {
    const [needAdjust, setNeedAdjust] = useState(false);
    const [coverage, setCoverage] = useState(0);
    const [confidence, setConfidence] = useState(DEFAULT_CONFIDENCE);
    const [loading, setLoading] = useState(false);
    const [form] = useForm();

    const handleConfidenceChange = (value) => {
      const confidence = Number(value);
      const _confidence = confidence ?? DEFAULT_CONFIDENCE;
      setConfidence(_confidence);
      onConfidenceChange(_confidence);
      form.setFieldsValue({ confidence: _confidence });
    };

    const deboucedFetcher = useDebounce((confidence) => {
      setLoading(true);
      onRequest?.();
      const _confidence = processConfidenceNumber(confidence);
      return requestWithoutCache(`/api/dmp/crowd/coverage`, {
        method: 'POST',
        data: JSON.stringify({
          type: 'extend_crowd',
          crowd_id: +crowd_id,
          confidence: +_confidence,
        }),
      }).then((res) => {
        setLoading(false);
        onSuccess?.(res.data);
        setCoverage(res.data?.coverage ?? 0);
      });
    }, 300);

    useEffect(() => {
      deboucedFetcher(confidence);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
      if (needAdjust) {
        deboucedFetcher(confidence);
      } else {
        deboucedFetcher(DEFAULT_CONFIDENCE);
        handleConfidenceChange(DEFAULT_CONFIDENCE);
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [confidence, deboucedFetcher, needAdjust]);

    useImperativeHandle(ref, () => {
      return {
        form,
      };
    });
    return (
      <div style={{ marginTop: '30px' }}>
        <Form form={form}>
          <Form.Item label="人群置信度调整">
            <Radio.Group
              value={needAdjust}
              options={[
                { label: '否', value: false },
                { label: '是', value: true },
              ]}
              onChange={(e) => {
                setNeedAdjust(e.target.value);
              }}
            />
          </Form.Item>
          <Form.Item
            hidden={true}
            name="confidence"
            initialValue={DEFAULT_CONFIDENCE}
          />
          {needAdjust && (
            <>
              <Form.Item label="置信度">
                <Space>
                  <InputNumber
                    step={0.1}
                    min={MIN_CONFIDENCE}
                    max={MAX_CONFIDENCE}
                    value={confidence}
                    onChange={handleConfidenceChange}
                  />
                  <span>
                    可选择置信度范围：{MIN_CONFIDENCE}-{MAX_CONFIDENCE}
                  </span>
                  <Tooltip
                    title="支持根据置信度圈选用户，置信度范国在0.50-1.00之间，注意置信
度越高，说明该用户和目标人群越相似。人数范国是根据置信度圈出的人群范围"
                  >
                    <QuestionCircleOutlined />
                  </Tooltip>
                </Space>
              </Form.Item>
              <span>
                人数范围：{minCoverage}-{maxCoverage}
              </span>
              <Form.Item label="人数">
                <Space>
                  <Spin spinning={loading}>
                    {!loading && <span>{coverage ?? '-'}</span>}
                  </Spin>
                </Space>
              </Form.Item>
            </>
          )}
        </Form>
      </div>
    );
  },
);

export default CrowdCountAdjust;
